/**
 * Created by Dalyn on 2017/3/17.
 * 企业-充值流程
 */
import React from "react";
import "./css/rechargeOrder.css";
import { hashHistory } from 'react-router';
import { message,Modal } from 'antd';
import Relay from "react-relay";
import RechargeMutation from './mutation/RechargeMutation';
import FileUpData from './components/FileUpDataPro'  //上传附件
import GetQiNiuToken from "./mutation/FindSewRawListMutation"  //上传图片获取token
import InputBox from "../../common/InputBox";
import { Button } from 'fly';
import Config from "../../util/Config"

/*导出组件*/
export default class RechargeOrder extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            invoiceFileJsonHint:false,
            token: '',
            remitFileJson:[],
            applyAmount: '',//充值金额
            applyAmountHint: '',
            remitFileJsonHint: '',
            isShow: 0,
            isPreview:false,
            previewImg:{curImgSrc:"",curImgName:""},   //当前图片预览链接
            highLight: false
        };
        this.priseAt = "88888888";
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.uid = sessionStorage.getItem('uid');
        this.username = sessionStorage.getItem('username');
        this.FixedImgSrc = Config.qiuniu;

        this.addFileItem = this.addFileItem.bind(this); //上传文件 更新内部状态list
        this.RechargeClick = this.RechargeClick.bind(this) //确认充值按钮点击
        this.changeInput = this.changeInput.bind(this) //监听input改变
        // this.imgDownload = this.imgDownload.bind(this)
        this.imgDelete = this.imgDelete.bind(this)

        // this.cancelPreview = this.cancelPreview.bind(this);
        // this.handlePreview = this.handlePreview.bind(this);
    }


    componentWillMount() {
      //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
    }
    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        accept:this.fileAccept,
        maxlength:1
    };

    //附件上传之前验证
    fileBeforeload(file){
        const MaxSize = 8;  //最大限度 10M;

        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("文件大小超过限制");
            return false;
        }

        if(file.type !== "image/jpeg" &&
          file.type !== "image/jpg" &&
          file.type !== "image/png" &&
          file.type !== "image/gif" &&
          file.type !== "image/bmp"){
            message.info('请上传8M以内的BMP、JPEG、JPG、GIF、PNG格式的文件')
            return false;
        }
    }

    // 新增文件函数，（push 当前组件）
    addFileItem(fileList){
        this.state.remitFileJson = fileList;
        this.setState({
            remitFileJson:this.state.remitFileJson,
            remitFileJsonHint: '',
            isShow: 1
        })
    }

    handleClickSelf(){
        message.warning("附件只允许上传1个")
    }

    // priseAccount() {
    //     return this.priseAt;
    // }
    imgDelete() {
      this.setState({
        remitFileJson: [],
        isShow: 0
      })
    }
    handlePreview(index){
        this.setState({
            isPreview:true,
            previewImg: {
                curImgSrc: this.FixedImgSrc + this.state.remitFileJson[0].response.key,
                curImgName: this.state.remitFileJson[0].name
            }
        })
    }

    cancelPreview(){
        this.setState({
            isPreview: false,
            previewImg: {
                curImgSrc: '',
                curImgName: ''
            }
        })
    }
    RechargeClick() {
        if (this.state.applyAmount == '') {
            this.setState({
                applyAmountHint: '请填写充值金额'
            })
            return
        }

        if (this.state.applyAmount < 1) {
            this.setState({
                applyAmountHint: '充值金额不得小于1元'
            })
            return
        }

        if (this.state.remitFileJson == '') {
            this.setState({
                remitFileJsonHint: '请上传汇款凭证'
            })
            return
        }

        if(this.state.remitFileJson[0].status !== "done"){
          message.config({
            top: 20,
            duration: 1.5,
          });
          message.info("请等待上传文件完成");
          return ;
        }
        this.Recharge()

    }

    Recharge() {
        Relay.Store.commitUpdate(
            new RechargeMutation({
                enid: this.enterpriseId,
                applyAmount: this.state.applyAmount,
                remitFileJson: JSON.stringify(this.state.remitFileJson),
                createByName: this.username,
                createBy: this.uid
            }), {
                onSuccess: (res) => {
                    let data = res.enterpriseApplyRecharge.data
                    if(data.errorCode==0){
                        message.success('充值成功')
                        hashHistory.push('/rechargerecordcompany')
                    } else{
                        message.error(data.value)
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
    }
    changeInput(e) {
        this.setState({
            applyAmountHint: ''
        })
        let text = e.target.value;
        let regular = /^[0-9]+\.?[0-9]{0,2}$/
        if(!regular.test(text) && text != ''){
            return
        } else if(text.length > 10) {
            return
        } else {
            this.setState({
                applyAmount: text
            });
        }
    }

    inputFocus() {
        this.setState({
            highLight: true
        })
    }
    inputBlur(){
        this.setState({
            highLight: false,
        })

    }

    render() {
        const { remitFileJson,token,remitFileJsonHint, applyAmountHint, isPreview, previewImg } = this.state

        return (
            <div style={{height:'inherit'}}>
                <div className="recharge_ord">
                    <div className="recharge_ord_box">
                        <div className="recharge_ord_circleBox clear">
                            <div className="recharge_ord_circle">
                                <p className="recharge_ord_step">
                                    <span>1</span>
                                    <span>2</span>
                                    <span></span>
                                </p>
                            </div>
                            <p className="recharge_ord_circle_text">
                                <span className="recharge_ord_circle_span">转账到平台</span>
                                <span className="recharge_ord_circle_span">确认收款</span>
                                <span className="recharge_ord_circle_span1">充值到企业账户</span>
                            </p>
                        </div>
                        <div className="recharge_ord_context">
                            <p style={{display: 'flex', alignItems:'center'}}><a className="recharge_ord_red">*</a><span>充值金额&nbsp;</span>
                                {/*<div style={{display:"inline-block",marginLeft:'20px'}}>*/}
                                    {/*<InputBox className="pro_overflow_inputSty recharge_ord_input"*/}
                                              {/*space={20}*/}
                                              {/*maxlength={22}*/}
                                              {/*ref={''}*/}
                                              {/*changeon={this.changeInput.bind(this)}*/}
                                              {/*value={this.state.applyAmount}*/}
                                    {/*/>*/}
                                {/*</div>&nbsp;&nbsp;元*/}
                                <input
                                    onFocus={this.inputFocus.bind(this)}
                                    onBlur={this.inputBlur.bind(this)}
                                    className="recharge_ord_input recharge_ord_input"
                                    value={this.state.applyAmount}
                                    style={this.state.highLight ? {'border':'1px solid #36b3b3'}:{}}
                                    onChange={this.changeInput}
                                    type="text"
                                />&nbsp;&nbsp;元
                                <span className="recharge_ord_red">&nbsp;&nbsp;{applyAmountHint}</span>
                            </p>
                            <p className="recharge_ord_conTitle">收款方信息：<span className="recharge_ord_conTitle_span">（以下信息是确保您充值到账的重要信息）</span>
                            </p>
                            <div className="recharge_ord_info">
                                <p className="recharge_ord_p">
                                    <span>收款账户名</span><span>：</span><span className="recharge_ord_span">青岛海福瑞贸易有限公司</span>
                                </p>
                                <p className="recharge_ord_p">
                                    <span>开户行</span><span>：</span><span className="recharge_ord_span">华夏银行青岛分行营业部</span>
                                </p>
                                <p className="recharge_ord_p">
                                    <span>收款账号</span><span>：</span><span className="recharge_ord_span">12050000000657601</span>
                                </p>
                                <p className="recharge_ord_p recharge_upload">
                                    <a className="recharge_ord_red">*</a>
                                    <span className='recharge_ord_upload_span' style={{position:'relative',fontSize:'14px'}}>汇款凭证 : &nbsp;&nbsp;</span>
                                      <FileUpData
                                          className="packagSteps_updataFile process_demandlook recharge_ord_width"
                                          filePlugin={this.fileUploadPlugin}
                                          fileList={remitFileJson}
                                          callBack={this.addFileItem}
                                          token={token}
                                          isShowTrigger={remitFileJson.length < this.fileUploadPlugin.maxlength}
                                          handleClickSelf={this.handleClickSelf}
                                          ref="fileUploading"
                                      />
                                    <span className="recharge_ord_hint">（文件最大8M，文件格式：BMP、JPEG、JPG、GIF、PNG）</span>
                                    {
                                      this.state.isShow ? (
                                        <span className="recharge_ord_view"><a onClick={this.handlePreview.bind(this)}>查看</a> <a onClick={this.imgDelete}>删除</a></span>
                                      ) : null
                                    }

                                    <span className="recharge_ord_red" style={{position:'absolute', left:'118px',bottom:'50px'}}>&nbsp;&nbsp;{remitFileJsonHint}</span>
                                </p>
                                {/*<p className="recharge_ord_p">企业账号：<span className="recharge_ord_span">{sessionStorage.getItem('enterpriseId')}</span></p>*/}
                            </div>
                            <div className="recharge_ord_context_img"></div>
                        </div>
                    </div>
                    <div style={{textAlign:'center',marginTop:'20px'}}><Button className="" onClick={this.RechargeClick.bind(this)}>立即充值</Button></div>
                    {/*<p className="recharge_ord_p_hint recharge_red">* 汇款时请务必填写正确企业账号</p>*/}
                    <Modal
                        className="production_preview"
                        visible={isPreview}
                        width={800}
                        footer={null}
                        onCancel={this.cancelPreview.bind(this)}
                    >
                        <img src={previewImg.curImgSrc} style={{ width: '100%' }} alt={previewImg.curImgName}/>
                    </Modal>
                </div>
            </div>

        )
    }
}
